package cn.bupt.adt.interceptor;

import cn.bupt.adt.util.NetDataAccessUtil;
import cn.bupt.adt.util.RedisUtil;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AppCheckInstiInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        if (token == null || "".equals(token)) {
            this.printMessage(response, "no token");
            return false;
        }
        if ("yanbiao".equals(token) || "zhangbing".equals(token) || "zhanghongtai".equals(token)) {
            return true;
        }
        //判断token是否存在或有效
        if (RedisUtil.exist(token)) {
            int userId = Integer.parseInt((String) RedisUtil.get(token));
            request.setAttribute("userId", userId);
            return true;
        }
        this.printMessage(response, "请登录");
        return false;
    }

    //向前端回写消息
    private void printMessage(HttpServletResponse response, String message) throws IOException {
        response.setContentType("text/json; charset=utf-8");
        response.setHeader("Cache-Control", "no-cache"); //取消浏览器缓存
        PrintWriter out = response.getWriter();
        out.println(JSONArray.toJSONString(NetDataAccessUtil.error(-1).content("").resultDesp(message)));
        out.flush();
        out.close();
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
